package com.jn.exam.question.controller;


import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jn.exam.HTMLUtil;
import com.jn.exam.JwtUtils;
import com.jn.exam.R;
import com.jn.exam.UUIDUtil;
import com.jn.exam.question.entity.*;
import com.jn.exam.question.entity.vo.PaperInfo;
import com.jn.exam.question.service.*;
import com.zaxxer.hikari.util.FastList;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 江南大学1033190417
 * @since 2022-02-06
 */
@RestController
@RequestMapping("/question/paper")
@Api(description = "出卷相关")
@SuppressWarnings("all")//有警告看着不爽，去掉
public class PaperController {

    @Autowired
    private PaperService paperService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private PaperQuestionService paperQuestionService;

    @Autowired
    private PersonalQuestionService personalQuestionService;

    @Autowired
    private PaperLogService paperLogService;

    @Autowired
    private OssFeignService ossFeignService;


    @Autowired
    private TeacherService teacherService;


    @ApiOperation("老师新建试卷")
    @PostMapping("createNewPaper")
    @Transactional
    public R createNewPaper(@RequestBody Paper paper, HttpServletRequest request, String message) {
        String teacherId = JwtUtils.getMemberIdByJwtToken(request);
        paper.setGmtCreate(new Date());
        paper.setGmtModified(new Date());
        paper.setStatus("1");//试卷为建立状态
        boolean isCreated = paperService.createNewPaper(teacherId, paper);
        boolean savePaperLog = paperLogService.savePaperLog(message, paper.getId());
        Map<String, Object> param = new HashMap<>();
        param.put("teacherId", teacherId);
        param.put("paperId", paper.getId());
        if (isCreated && savePaperLog) {
            return R.ok().message("新建成功");
        }
        return R.error().message("添加失败");
    }

    /**
     * @param paper   新试卷相关信息
     * @param paperId 原试卷id
     * @return 成功
     */
    @ApiOperation("复制试卷")
    @PostMapping("pastePaper")
    @Transactional
    public R pastePaper(@RequestBody Paper paper, String paperId, HttpServletRequest request) {
        //先建立好试卷
        paper.setId(UUIDUtil.getUUID()).setStatus("2").setGmtCreate(new Date()).setGmtModified(new Date());
        boolean isOK1 = paperService.savePaper(paper);
        //在添加联系
        String teacherId = JwtUtils.getMemberIdByJwtToken(request);
        Map<String, Object> param = new HashMap<>();
        param.put("teacherId", teacherId);
        param.put("paperId", paper.getId());
        param.put("permission", "1");
        boolean save = paperService.inviteOneTeacherForPaper(param);
        //再复制试题
        QueryWrapper<PaperQuestion> wrapper = new QueryWrapper<>();
        wrapper.eq("paper_id", paperId);
        List<PaperQuestion> paperQuestions = paperQuestionService.list(wrapper);
        for (PaperQuestion paperQuestion : paperQuestions) {
            String name = paperQuestion.getName();
            String answer = paperQuestion.getAnswer();
            List<String> nameUrl = HTMLUtil.getUrl(name);
            List<String> answerUrl = HTMLUtil.getUrl(answer);
            for (String url : nameUrl) {
                String newUrl = ossFeignService.copyFileByUrl(url);
                name = name.replaceAll(url, newUrl);
            }
            for (String url : answerUrl) {
                String newUrl = ossFeignService.copyFileByUrl(url);
                answer = answer.replaceAll(url, newUrl);
            }
            PaperQuestion question = new PaperQuestion();
            question.setName(name).setAnswer(answer).setPaperId(paper.getId()).setType(paperQuestion.getType()).setLocation(paperQuestion.getLocation()).setScore(paperQuestion.getScore());
            paperQuestionService.save(question);
        }
        return R.ok().message("复制成功");
    }

    @ApiOperation("老师修改试卷附属信息包括状态")
    @PostMapping("updatePaperInfo")
    @Transactional
    public R updatePaperInfo(@RequestBody Paper paper, String message) {
        boolean updateById = paperService.updateById(paper);
        boolean savePaperLog = paperLogService.savePaperLog(message, paper.getId());
        if (updateById && savePaperLog) {
            return R.ok().message("更新成功");
        }
        return R.error().message("更新失败");
    }

    @ApiOperation("老师查询与自己相关的试卷")
    @GetMapping("getRelatedPaper")
    public R getRelatedPaper(HttpServletRequest request) {
        String teacherId = JwtUtils.getMemberIdByJwtToken(request);
        //String teacherId = "645c7a2029ae4396a00c00af64eeb3ee";
        List<PaperInfo> papers = paperService.getRelatedPaper(teacherId);
        if (papers != null) {
            return R.ok().data("papers", papers);
        }
        return R.error().message("查询失败");
    }


    /**
     * @param paperId            试卷id
     * @param personalQuestionId 个人题库题目id
     * @param location           题目在试卷中位置
     * @param message            添加日志  某某某向添加选择题第几题
     * @return R
     */
    @ApiOperation("老师往试卷中添加自己题库试题")
    @PostMapping("addPersonalQuestionToPaper")
    @Transactional
    public R addPersonalQuestionToPaper(String paperId, String personalQuestionId, Float location, String message, Float score) {
        PersonalQuestion personalQuestion = personalQuestionService.getById(personalQuestionId);
        PaperQuestion paperQuestion = new PaperQuestion();
        String name = personalQuestion.getName();
        String answer = personalQuestion.getAnswer();
        List<String> nameUrl = HTMLUtil.getUrl(name);
        List<String> answerUrl = HTMLUtil.getUrl(answer);
        if (!nameUrl.isEmpty()) {
            for (String url : nameUrl) {
                String u = ossFeignService.copyFileByUrl(url);
                name = name.replaceAll(url, u);
            }
        }
        if (!answerUrl.isEmpty()) {
            for (String url : answerUrl) {
                String u = ossFeignService.copyFileByUrl(url);
                answer = answer.replaceAll(url, u);
            }
        }
        paperQuestion.setName(name);
        paperQuestion.setAnswer(answer);
        paperQuestion.setScore(score);
        paperQuestion.setLocation(location);
        paperQuestion.setPaperId(paperId);
        paperQuestion.setType(personalQuestion.getType());
        boolean save = paperQuestionService.save(paperQuestion);
        boolean savePaperLog = paperLogService.savePaperLog(message, paperId);
        if (save && savePaperLog) {
            return R.ok().message("添加成功");
        }
        return R.error().message("添加失败");
    }

    @ApiOperation("老师添加总题库试题")
    @PostMapping("addQuestionToPaper")
    @Transactional
    public R addQuestionToPaper(String paperId, String questionId, Float location, String message, Float score) {
        Question question = questionService.getById(questionId);
        PaperQuestion paperQuestion = new PaperQuestion();
        String name = question.getName();
        String answer = question.getAnswer();
        List<String> nameUrl = HTMLUtil.getUrl(name);
        List<String> answerUrl = HTMLUtil.getUrl(answer);
        if (!nameUrl.isEmpty()) {
            for (String url : nameUrl) {
                String u = ossFeignService.copyFileByUrl(url);
                name = name.replaceAll(url, u);
            }
        }
        if (!answerUrl.isEmpty()) {
            for (String url : answerUrl) {
                String u = ossFeignService.copyFileByUrl(url);
                answer = answer.replaceAll(url, u);
            }
        }
        paperQuestion.setName(name);
        paperQuestion.setAnswer(answer);
        paperQuestion.setScore(score);
        paperQuestion.setLocation(location);
        paperQuestion.setPaperId(paperId);
        paperQuestion.setType(question.getType());
        boolean save = paperQuestionService.save(paperQuestion);
        boolean savePaperLog = paperLogService.savePaperLog(message, paperId);
        if (save && savePaperLog) {
            return R.ok().message("添加成功");
        }
        return R.error().message("添加失败");
    }


    /*
        [
      {
        "questionId": "a",
        "location": 1,
        "score": 2
      },
      {
        "questionId": "b",
        "location": 2,
        "score": 2
      },
      {
        "questionId": "c",
        "location": 3,
        "score": 2
      }
    ]
         */
    @ApiOperation("批量或单个添加总题库试题")
    @PostMapping("addPaperQuestionFromTotal")
    @Transactional
    public R addPaperQuestionFromTotal(@RequestBody List<Map<String, Object>> param, String paperId, String message) throws Exception {
        List<Future<Boolean>> futures = new ArrayList<>();
        for (Map<String, Object> map : param) {
            String questionId = (String) map.get("questionId");
            Float location = Convert.toFloat(map.get("location"));
            Float score = Convert.toFloat(map.get("score"));
            Future<Boolean> future = paperQuestionService.addQuestionToPaper(paperId, questionId, location, score);
            futures.add(future);
        }
        for (Future<Boolean> future : futures) {
            Boolean isOK = future.get();
            if (!isOK) {
                return R.error().message("添加失败");
            }
        }
        boolean savePaperLog = paperLogService.savePaperLog(message, paperId);
        if (savePaperLog) {
            return R.ok().message("添加成功");
        }
        return R.error().message("添加失败");
    }


    /*
        [
      {
        "personalQuestionId": "a",
        "location": 1,
        "score": 2
      },
      {
        "personalQuestionId": "b",
        "location": 2,
        "score": 2
      },
      {
        "personalQuestionId": "c",
        "location": 3,
        "score": 2
      }

    ]
         */
    @ApiOperation("批量化或单个添加个人题库试题")
    @PostMapping("addPaperQuestionFromPersonal")
    @Transactional
    public R addPaperQuestionFromPersonal(@RequestBody List<Map<String, Object>> param, String paperId, String message) throws Exception {
        List<Future<Boolean>> futures = new ArrayList<>();
        for (Map<String, Object> map : param) {
            String personalQuestionId = (String) map.get("personalQuestionId");
            Float location = Convert.toFloat(map.get("location"));
            Float score = Convert.toFloat(map.get("score"));
            Future<Boolean> future = paperQuestionService.addPersonalQuestionToPaper(paperId, personalQuestionId, location, score);
            futures.add(future);
        }
        for (Future<Boolean> future : futures) {
            Boolean isOK = future.get();
            if (!isOK) {
                return R.error().message("添加失败");
            }
        }
        boolean savePaperLog = paperLogService.savePaperLog(message, paperId);
        if (savePaperLog) {
            return R.ok().message("添加成功");
        }
        return R.error().message("添加失败");
    }


    @ApiOperation("智能组卷，查看满足用户输入的条件共有几题")
    @PostMapping("getCountIntelligent")
    public R getCountIntelligent(@RequestBody Map<String, Object> param) {
        String type = (String) param.get("type");//题型
        String[] majors = Convert.toStrArray(param.get("major"));//专业
        String[] subjects = Convert.toStrArray(param.get("subject"));//科目
        String[] storeIds = Convert.toStrArray(param.get("storeIds"));//个人题库
        Integer[] levelBetween = Convert.toIntArray(param.get("levelBetween"));
        Integer[] levelStartEnd = Convert.toIntArray(param.get("levelStartEnd"));
        QueryWrapper<PersonalQuestion> wrapper = new QueryWrapper<>();
        wrapper.eq("type", type).in("store_id", storeIds);
        if (majors != null && majors.length != 0) {
            wrapper.in("major", majors);
        }
        if (subjects != null && subjects.length != 0) {
            wrapper.in("subject", subjects);
        }
        if (levelBetween != null && levelBetween.length != 0) {
            wrapper.in("level", levelBetween);
        }
        if (levelStartEnd != null && levelStartEnd.length != 0) {
            wrapper.between("level", levelStartEnd[0], levelStartEnd[1]);
        }
        int count = personalQuestionService.count(wrapper);
        return R.ok().data("count", count);
    }


    /*
       [
       {
         type:1,           (string)  题型
         number: 5,        (Integer) 数量
         score: 3.0
         major: [] ,       数组       专业
         subject:[],                 科目
         storeIds:[],                选择的个人题库
         levelBetween:[1,2,3]        难度的等级，指定几个难度等级
         levelStartEnd:[1,5]         难度的区间  只能是闭区间       以上两个二选一

         以上全部条件除了题型，数量,分值和题库，其他都可为空,每题默认分值都一样，如需修改组完卷再说
       },
       ]
     */
    @ApiOperation("智能组卷，只支持从个人题库中选择")
    @PostMapping("intelligentPaper")
    @Transactional
    public R intelligentPaper(@RequestBody List<Map<String, Object>> param, String paperId, String message) throws Exception {
        List<Future<Boolean>> futures = new ArrayList<>();
        for (Map<String, Object> map : param) {
            String type = (String) map.get("type");//题型
            Integer number = Convert.toInt(map.get("number"));//数量
            Float score = Convert.toFloat(map.get("score"));
            String[] majors = Convert.toStrArray(map.get("major"));//专业
            String[] subjects = Convert.toStrArray(map.get("subject"));//科目
            String[] storeIds = Convert.toStrArray(map.get("storeIds"));//个人题库
            Integer[] levelBetween = Convert.toIntArray(map.get("levelBetween"));
            Integer[] levelStartEnd = Convert.toIntArray(map.get("levelStartEnd"));
            QueryWrapper<PersonalQuestion> wrapper = new QueryWrapper<>();
            wrapper.select("id").eq("type", type).in("store_id", storeIds).last("  ORDER BY `level`, RAND() LIMIT " + number);
            if (majors != null && majors.length != 0) {
                wrapper.in("major", majors);
            }
            if (subjects != null && subjects.length != 0) {
                wrapper.in("subject", subjects);
            }
            if (levelBetween != null && levelBetween.length != 0) {
                wrapper.in("level", levelBetween);
            }
            if (levelStartEnd != null && levelStartEnd.length != 0) {
                wrapper.between("level", levelStartEnd[0], levelStartEnd[1]);
            }
            List<String> personalQuestionIds = personalQuestionService.list(wrapper).stream().map(PersonalQuestion::getId).collect(Collectors.toList());
            if (personalQuestionIds != null && personalQuestionIds.size() != 0) {
                for (int i = 0; i < personalQuestionIds.size(); i++) {
                    Future<Boolean> future = paperQuestionService.addPersonalQuestionToPaper(paperId, personalQuestionIds.get(i), Convert.toFloat(i), score);
                    futures.add(future);
                }
            }
        }
        for (Future<Boolean> future : futures) {
            Boolean b = future.get();
            if (!b) {
                return R.error().message("组卷失败");
            }
        }
        boolean b = paperLogService.savePaperLog(message, paperId);
        if (!b) {
            return R.error().message("组卷失败");
        }
        return R.ok().message("组卷成功");
    }


    /*
         [
        {
            "paperQuestionId": "a",
                "location": 1,
        },
        {
            "paperQuestionId": "b",
                "location": 2,
        },
        {
            "paperQuestionId": "c",
                "location": 3,
        }

        ]

     */
    @ApiOperation("确定所有题目位置")
    @PostMapping("confirmAllPaperQuestionLocation")
    @Transactional
    public R confirmAllPaperQuestionLocation(@RequestBody List<Map<String, Object>> param, String paperId, String message) {
        for (Map<String, Object> map : param) {
            String paperQuestionId = (String) map.get("paperQuestionId");
            Float location = Convert.toFloat(map.get("location"));
            PaperQuestion paperQuestion = new PaperQuestion();
            paperQuestion.setId(paperQuestionId).setLocation(location);
            boolean update = paperQuestionService.updateById(paperQuestion);
            if (!update) {
                return R.ok().message("失败");
            }
        }
        boolean b = paperLogService.savePaperLog(message, paperId);
        if (b) {
            return R.ok().message("成功");
        }
        return R.ok().message("失败");
    }

    @ApiOperation("老师自定义添加试题")
    @PostMapping("addCustomizeQuestionToPaper")
    @Transactional
    public R addCustomizeQuestionToPaper(@RequestBody PaperQuestion paperQuestion, String message) {
        boolean save = paperQuestionService.save(paperQuestion);
        boolean save1 = paperLogService.savePaperLog(message, paperQuestion.getPaperId());
        if (save && save1) {
            return R.ok().message("添加成功");
        }
        return R.error().message("添加失败");
    }

    @ApiOperation("根据id查询试卷试题")
    @GetMapping("getPaperQuestionById/{paperQuestionId}")
    public R getPaperQuestionById(@PathVariable("paperQuestionId") String paperQuestionId) {
        PaperQuestion paperQuestion = paperQuestionService.getById(paperQuestionId);
        return R.ok().data("paperQuestion", paperQuestion);
    }

    @ApiOperation("根据两题id互换位置")
    @PostMapping("exchangeLocationById")
    public R exchangeLocationById(String id1, String id2, String paperId, String message) {
        Map<String, Object> param = new HashMap<>();
        param.put("id1", id1);
        param.put("id2", id2);
        boolean isOK = paperQuestionService.exchangeLocationById(param);
        boolean isOK2 = paperLogService.savePaperLog(message, paperId);
        if (isOK && isOK2) {
            return R.ok().message("交换成功");
        }
        return R.error().message("交换失败");
    }

    @ApiOperation("查询一张试卷")
    @PostMapping("getPaperInventory")
    public R getPaperInventory(String paperId) {
        QueryWrapper<PaperQuestion> wrapper = new QueryWrapper<>();
        wrapper.eq("paper_id", paperId).orderByAsc("type").orderByAsc("location");
        List<PaperQuestion> paperQuestions = paperQuestionService.list(wrapper);
        QueryWrapper<PaperLog> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("paper_id", paperId).orderByDesc("gmt_create");
        List<PaperLog> paperLogs = paperLogService.list(wrapper1);
        Map<String, List<PaperQuestion>> stringListMap = paperQuestionSplit(paperQuestions);
        return R.ok().data("question", stringListMap).data("logs", paperLogs);
    }

    @ApiOperation("考生参加考试初次拿到试卷")
    @PostMapping("takeOneExamFirst")
    @Cacheable("paper")
    public R takeOneExamFirst(String paperId) {
        QueryWrapper<PaperQuestion> wrapper = new QueryWrapper<>();
        wrapper.eq("paper_id", paperId).orderByAsc("type").orderByAsc("location")
                .select("id", "name", "score", "location", "paper_id", "version", "type");
        List<PaperQuestion> paperQuestions = paperQuestionService.list(wrapper);
        Map<String, List<PaperQuestion>> stringListMap = paperQuestionSplit(paperQuestions);
        return R.ok().data("question", stringListMap);
    }


    @ApiOperation("考生参加考试拿到试卷试题,考虑考一半中途退场要返回之前已经填写的答案")
    @PostMapping("takeOneExam")
    public R takeOneExam(String paperId, HttpServletRequest request) {
        String studentId = JwtUtils.getMemberIdByJwtToken(request);
        List<PaperQuestion> paperQuestions = paperQuestionService.takeOneExam(paperId, studentId);
        Map<String, List<PaperQuestion>> stringListMap = paperQuestionSplit(paperQuestions);
        return R.ok().data("question", stringListMap);
    }

    @ApiOperation("老师阅卷拿到试题，包括正确答案和学生答案，题目分数，学生得分")
    @PostMapping("markingStudentPaper")
    @Transactional
    public R markingStudentPaper(String examId, String paperId, String studentId) {
        List<PaperQuestion> paperQuestions = paperQuestionService.markingStudentPaper(paperId, studentId);
        Map<String, List<PaperQuestion>> stringListMap = paperQuestionSplit(paperQuestions);
        return R.ok().data("question", stringListMap);
    }


    @ApiOperation("学生拿到批改完的试卷")
    @GetMapping("getMarkedPaper")
    public R getMarkedPaper(String examId, String paperId, String studentId) {
        List<PaperQuestion> paperQuestions = paperQuestionService.markingStudentPaper(paperId, studentId);
        Map<String, List<PaperQuestion>> stringListMap = paperQuestionSplit(paperQuestions);
        return R.ok().data("question", stringListMap);
    }

    @ApiOperation("查询试卷总分")
    @GetMapping("getTotalScoreOfPaper")
    public R getTotalScoreOfPaper(String paperId) {
        Float totalScore = paperService.getTotalScoreOfPaper(paperId);
        return R.ok().data("totalScore", totalScore);
    }


    @ApiOperation("删除一张试卷")
    @DeleteMapping("deleteOnePaper")
    @Transactional
    public R deleteOnePaper(String paperId) {
        //先删除试卷上的题目
        QueryWrapper<PaperQuestion> wrapper = new QueryWrapper<>();
        wrapper.eq("paper_id", paperId);
        boolean removeQuestion = paperQuestionService.remove(wrapper);
        //删除试卷日志
        QueryWrapper<PaperLog> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("paper_id", paperId);
        boolean removePaperLog = paperLogService.remove(wrapper1);
        //删除试卷与老师的联系
        boolean removePaperTeacherConnection = paperService.removePaperTeacherConnection(paperId);
        //删除试卷
        boolean removePaper = paperService.removeById(paperId);
        return R.ok().message("删除成功");
    }

    @ApiOperation("删除试卷的某一题")
    @DeleteMapping("deleteOnePaperQuestion")
    @Transactional(rollbackFor = Exception.class)
    public R deleteOnePaperQuestion(String paperQuestionId, String message, String paperId) {
        PaperQuestion paperQuestion = paperQuestionService.getById(paperQuestionId);
        String name = paperQuestion.getName();
        String answer = paperQuestion.getAnswer();
        List<String> nameUrl = HTMLUtil.getUrl(name);
        List<String> answerUrl = HTMLUtil.getUrl(answer);
        for (String url : nameUrl) {
            ossFeignService.deleteFileByUrl(url);
        }
        for (String url : answerUrl) {
            ossFeignService.deleteFileByUrl(url);
        }
        paperQuestionService.removeById(paperQuestionId);
        paperLogService.savePaperLog(message, paperId);
        return R.ok().message("删除成功");
    }

    @ApiOperation("更新试卷某一题")
    @PostMapping("updatePaperQuestion")
    public R updatePaperQuestion(@RequestBody PaperQuestion paperQuestion) {
        boolean updateById = paperQuestionService.updateById(paperQuestion);
        if (updateById) {
            return R.ok().message("更新成功");
        }
        return R.error().message("更新失败");
    }


    /**
     * @param teacherId  老师id
     * @param paperId    试卷id
     * @param permission 权限
     * @return
     */
    @ApiOperation("邀请某老师一起管理试卷")
    @PostMapping("inviteOneTeacherForPaper")
    public R inviteOneTeacherForPaper(String teacherId, String paperId, String permission) {
        Map<String, Object> param = new HashMap<>();
        param.put("teacherId", teacherId);
        param.put("paperId", paperId);
        param.put("permission", permission);
        List<Map<String, Object>> connection = paperService.ifHasTeacherPaperConnection(param);
        if (connection != null && !connection.isEmpty()) {
            return R.error().message("该老师与该试卷存在联系");
        }
        boolean save = paperService.inviteOneTeacherForPaper(param);
        if (save) {
            return R.ok().message("邀请成功");
        }
        return R.error().message("邀请失败");
    }


    @ApiOperation("更改某老师权限")
    @PostMapping("updatePaperPermissionForTeacher")
    public R updatePaperPermissionForTeacher(String teacherId, String paperId, String permission) {
        Map<String, Object> param = new HashMap<>();
        param.put("teacherId", teacherId);
        param.put("paperId", paperId);
        param.put("permission", permission);
        boolean update = paperService.updatePaperPermissionForTeacher(param);
        if (update) {
            return R.ok().message("更新成功");
        }
        return R.error().message("更新失败");
    }

    @ApiOperation("移除某老师与某试卷的联系")
    @PostMapping("deleteTeacherFromPaper")
    public R deleteTeacherFromPaper(String teacherId, String paperId) {
        Map<String, Object> param = new HashMap<>();
        param.put("teacherId", teacherId);
        param.put("paperId", paperId);
        boolean delete = paperService.deleteTeacherFromPaper(param);
        if (delete) {
            return R.ok().message("移除成功");
        }
        return R.error().message("移除失败");
    }

    @ApiOperation("按姓名查询某老师的全部信息")
    @GetMapping("getTeacherByName")
    public R getTeacherByName(String name) {
        QueryWrapper<Teacher> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(name)) {
            wrapper.like("name", name);
        }
        List<Teacher> teachers = teacherService.list(wrapper);
        if (teachers != null) {
            return R.ok().data("teachers", teachers);
        }
        return R.error().message("查询失败");
    }

    @ApiOperation("将试卷提交审核")
    @PostMapping("submitPaper")
    @Transactional
    public R submitPaper(String paperId) {
        Paper paper = new Paper();
        paper.setId(paperId);
        paper.setStatus("4");//试卷为提交审核阶段
        boolean update = paperService.updateById(paper);
        if (update) {
            return R.ok().message("提交成功");
        }
        return R.error().message("提交失败");
    }

    /**
     * 1	建立
     * 2	编辑
     * 3	完工
     * 4	提交审核
     * 5	审核不通过
     * 6	可发布考试
     *
     * @param status
     * @return
     */
    @ApiOperation("查询所有审核或未审核或审核不通过的试卷")
    @GetMapping("getAllNoPassedPaper")
    public R getAllNoPassedPaper(String status) {
        List<PaperInfo> papers = paperService.getAllStatusPaperInfo(status);
        return R.ok().data("papers", papers);
    }

    @ApiOperation("审核某一张试卷")
    @PostMapping("passPaper")
    public R passPaper(String paperId, boolean isOK) {
        Paper paper = new Paper();
        paper.setId(paperId);
        String status = isOK ? "6" : "5";
        paper.setStatus(status);
        boolean update = paperService.updateById(paper);
        if (update) {
            return R.ok().message("审核成功");
        }
        return R.error().message("审核错误");
    }

    private Map<String, List<PaperQuestion>> paperQuestionSplit(List<PaperQuestion> paperQuestions) {
        Map<String, List<PaperQuestion>> paperQuestionInventory = new HashMap<>();
        for (int i = 0; i < paperQuestions.size(); i++) {
            PaperQuestion paperQuestion = paperQuestions.get(i);
            String type = paperQuestion.getType();
            if (paperQuestionInventory.containsKey(type)) {
                paperQuestionInventory.get(type).add(paperQuestion);
            } else {
                List<PaperQuestion> paperQuestionList = new ArrayList<>();
                paperQuestionList.add(paperQuestion);
                paperQuestionInventory.put(type, paperQuestionList);
            }
        }
        return paperQuestionInventory;
    }


}

